package internal

import (
	"encoding/binary"
	"errors"
)

type HintItem struct {
	Timestamp     int64
	KeySize       uint32
	ValueSize     uint32
	ValuePosition int64
	Key           []byte
}

func (it *HintItem) Encode() []byte {
	data := make([]byte, 8+4+4+8)
	binary.BigEndian.PutUint64(data[:8], uint64(it.Timestamp))
	binary.BigEndian.PutUint32(data[8:12], it.KeySize)
	binary.BigEndian.PutUint32(data[12:16], it.ValueSize)
	binary.BigEndian.PutUint64(data[16:24], uint64(it.ValuePosition))
	data = append(data, it.Key...)
	return data
}

func (it *HintItem) DecodeHeader(header []byte) error {
	if len(header) < 24 {
		return errors.New("hint data is not valid")
	}
	it.Timestamp = int64(binary.BigEndian.Uint64(header[0:8]))
	it.KeySize = binary.BigEndian.Uint32(header[8:12])
	it.ValueSize = binary.BigEndian.Uint32(header[12:16])
	it.ValuePosition = int64(binary.BigEndian.Uint64(header[16:24]))
	return nil
}

func (it *HintItem) Decode(data []byte) error {
	it.DecodeHeader(data)
	it.Key = data[24 : 24+it.KeySize]
	return nil
}
